package com.suning.sawp.service.impl.returngoods;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.dto.returngoods.BrandStatis;
import com.suning.sawp.dto.returngoods.OosCateBrandStatis;
import com.suning.sawp.dto.returngoods.OosStatisDetailRtn;
import com.suning.sawp.dto.returngoods.OosStatisRtn;
import com.suning.sawp.dto.returngoods.StoreOosHomeShowDto;
import com.suning.sawp.dto.storeman.BrandInfo;
import com.suning.sawp.dto.storeman.Category;
import com.suning.sawp.intf.dao.BiStoreOosDaoService;
import com.suning.sawp.intf.returngoods.StoreOosService;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.po.bi.BiStoreOosDetailEntity;
import com.suning.sawp.po.bi.BiStoreOosEntity;
import com.suning.sawp.service.util.ConfigUtil;

@Service("storeOosService")
public class StoreOosServiceImpl implements StoreOosService {

    /**
     * 门店整体缺货
     */
    private static final String GENERAL_OOS = "1";
    /**
     * 门店热销
     */
    private static final String HOT_OOS = "3";
    /**
     * 门店主推
     */
    private static final String MAIN_PUSH_OOS = "2";
    
    private static final String SUM = "1";
    
    @Resource
    StoreManService storeManService;
    
    @Resource
    BiStoreOosDaoService biStoreOosDaoService;
    
    @Override
    public ReturnMsg<List<StoreOosHomeShowDto>> queryOosHomeDataShow(String staffId) {
        ReturnMsg<List<StoreOosHomeShowDto>> returnMsg = new ReturnMsg<List<StoreOosHomeShowDto>>();
        List<StoreOosHomeShowDto> dtos = new ArrayList<StoreOosHomeShowDto>();
        // 取店员信息
        StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
        String storeCode = storeMan.getStoreCode();
        if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
            // 店长
            // 门店整体
            OosStatisRtn generalOos = biStoreOosDaoService.queryStoreGeneralOosStatis(storeCode);
            // 门店热销
            OosStatisRtn hotOos = biStoreOosDaoService.queryStoreHotOosStatis(storeCode);
            // 门店主推
            OosStatisRtn mainpushOos = biStoreOosDaoService.queryStoreMainPushOosStatis(storeCode);
            StoreOosHomeShowDto showDto = new StoreOosHomeShowDto();
            if (null != generalOos) {
                showDto.setGeneralOosNum(generalOos.getOosNum());
            }
            if (null != hotOos) {
                showDto.setHotOosNum(hotOos.getOosNum());
                showDto.setHotOosRate(hotOos.getOosRate()); 
            }
            if (null != mainpushOos) {
                showDto.setMainPushOosNum(mainpushOos.getOosNum());
                showDto.setMainPushOosRate(mainpushOos.getOosRate());
            }
            dtos.add(showDto);
        } else if (ClerkConstants.SALE_GUIDE.equals(storeMan.getPositionId())) {
            // 督导
            // 取督导品类信息
            Set<String> cateCodes = new HashSet<String>();
            for (Category category : storeMan.getCategories()) {
                cateCodes.add(category.getCategoryCode());
            }
            // 门店整体
            List<OosStatisRtn> generalCateOos = biStoreOosDaoService.queryStoreCateGeneralOosStatis(storeCode, cateCodes);
            // 门店热销
            List<OosStatisRtn> hotCateOos = biStoreOosDaoService.queryStoreCateHotOosStatis(storeCode, cateCodes);
            // 门店主推
            List<OosStatisRtn> mainpushCateOos = biStoreOosDaoService.queryStoreCateMainPushOosStatis(storeCode, cateCodes);
            // 组装各品类门店整体、热销、主推缺货统计数据
            for (String cateCode : cateCodes) {
                StoreOosHomeShowDto showDto = new StoreOosHomeShowDto();
                showDto.setCategoryCode(cateCode);
                showDto.setCategoryName(ConfigUtil.getConfig(ConfigConstants.SAWP_CONFIG_MAIN_PUSH_CATEGORY, cateCode));
                // 门店整体
                for (OosStatisRtn rtn : generalCateOos) {
                    if (cateCode.equals(rtn.getCateCode())) {
                        showDto.setGeneralOosNum(rtn.getOosNum());
                        break;
                    }
                }
                // 门店热销
                for (OosStatisRtn rtn : hotCateOos) {
                    if (cateCode.equals(rtn.getCateCode())) {
                        showDto.setHotOosNum(rtn.getOosNum());
                        showDto.setHotOosRate(rtn.getOosRate());
                        break;
                    }
                }
                // 门店主推
                for (OosStatisRtn rtn : mainpushCateOos) {
                    if (cateCode.equals(rtn.getCateCode())) {
                        showDto.setMainPushOosNum(rtn.getOosNum());
                        showDto.setMainPushOosRate(rtn.getOosRate());
                        break;
                    }
                }
                
                dtos.add(showDto);
            }
            
        }
        returnMsg.setData(dtos);
        return returnMsg;
    }

    @Override
    public ReturnMsg<BrandStatis> queryOosBrandList(String staffId, String cateCodes, String queryType) {
        ReturnMsg<BrandStatis> returnMsg = new ReturnMsg<BrandStatis>();
        BrandStatis statis = new BrandStatis();
        // 取店员信息
        StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
        String storeCode = storeMan.getStoreCode();
        // 放置所有归属品类
        statis.setCategories(storeMan.getCategories());
        Set<String> cateCodeSet = new HashSet<String>();
        if (StringUtils.isNotBlank(cateCodes)) {
            String[] cateCds = cateCodes.split(",");
            for (String cateCd : cateCds) {
                cateCodeSet.add(cateCd);
            }
        }
        
        if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
            if (CollectionUtils.isEmpty(cateCodeSet)) {
                // 如果店长所传品类为空，则默认按所属8大品类处理
                for (Category cate : storeMan.getCategories()) {
                    cateCodeSet.add(cate.getCategoryCode());
                }
            }
        }
        
        List<BiStoreOosEntity> oosBrands = null;
        if (GENERAL_OOS.equals(queryType)) {
            oosBrands = biStoreOosDaoService.queryStoreGeneralOosBrandStatis(storeCode, cateCodeSet);
        } else if (HOT_OOS.equals(queryType)) {
            oosBrands = biStoreOosDaoService.queryStoreHotOosBrandStatis(storeCode, cateCodeSet);
        } else if (MAIN_PUSH_OOS.equals(queryType)) {
            oosBrands = biStoreOosDaoService.queryStoreMainPushOosBrandStatis(storeCode, cateCodeSet);
        }
        List<BrandInfo> brands = new ArrayList<BrandInfo>();
        if (CollectionUtils.isNotEmpty(oosBrands)) {
            // 品牌编码4位-9位列表关系
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            // 品牌编码4位-品牌名称关系
            Map<String, String> brandMap = new HashMap<String, String>();
            for (BiStoreOosEntity entity : oosBrands) {
                List<String> brand9codes = map.get(entity.getBrand4code());
                if (null == brand9codes) {
                    brand9codes = new ArrayList<String>();
                    map.put(entity.getBrand4code(), brand9codes);
                }
                brand9codes.add(entity.getBrand9code());
                brandMap.put(entity.getBrand4code(), entity.getBrandName());
            }
            
            // 组装所需数据
            Set<Entry<String, String>> entries = brandMap.entrySet();
            for (Entry<String, String> entry : entries) {
                BrandInfo brandInfo = new BrandInfo();
                brandInfo.setBranch4code(entry.getKey());
                brandInfo.setBranch9codes(map.get(entry.getKey()));
                brandInfo.setBranchName(entry.getValue());
                
                brands.add(brandInfo);
            }
        }
        
        statis.setBranches(brands);
        returnMsg.setData(statis);
        return returnMsg;
    }

    @Override
    public ReturnMsg<List<OosCateBrandStatis>> queryOosStatisList(String brandCodes, String categoryCodes, int limit,
            String queryType, int startIndex, String sumType, String staffId) {
        ReturnMsg<List<OosCateBrandStatis>> returnMsg = new ReturnMsg<List<OosCateBrandStatis>>();
        // 取店员信息
        StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
        String storeCode = storeMan.getStoreCode();
        Set<String> brandCodeSet = new HashSet<String>();
        Set<String> cateCodeSet = new HashSet<String>();
        // 优先按品牌查询
        if (StringUtils.isNotBlank(brandCodes)) {
            // 查询品牌对应的缺货统计
            String[] args = brandCodes.split(",");
            for (String brandCd : args) {
                brandCodeSet.add(brandCd);
            }
        } else {
            // 品牌为空，则查询品类
            if (StringUtils.isNotBlank(categoryCodes)) {
                String[] args = categoryCodes.split(",");
                for (String cateCd : args) {
                    cateCodeSet.add(cateCd);
                }
            } else {
                // 品牌编码为空、品类编码为空，并判断此用户为店长
                if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
                    // 取店长的八大品类
                    for (Category cate : storeMan.getCategories()) {
                        cateCodeSet.add(cate.getCategoryCode());
                    }
                }
            }
        }
        
        List<OosCateBrandStatis> data = null;
        if (CollectionUtils.isNotEmpty(brandCodeSet)) {
            // 按9位品牌编码查询
            data = getOosStatisByBrand9codes(storeCode, brandCodeSet, queryType, sumType, startIndex, limit);
        } else {
            if (CollectionUtils.isNotEmpty(cateCodeSet)) {
                if (!SUM.equals(sumType)) {
                    // 按品类查询，不汇总
                    data = getOosCateBrandStatisByCateCd(storeCode, cateCodeSet, startIndex, limit, queryType, sumType);
                } else {
                    // 按品类查询，汇总展示
                    data = getOosCateStatisByCateCd(storeCode, cateCodeSet, startIndex, limit, queryType, sumType);
                }
            }
        }
            
        returnMsg.setData(data);
        return returnMsg;
    }
    
    /**
     * 
     * 功能描述: 根据9位品牌编码查询<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param brandCodes
     * @param queryType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<OosCateBrandStatis> getOosStatisByBrand9codes(String storeCode, 
            Set<String> brandCodes, String queryType, String sumType,  int startIndex, int limit) {
        List<OosCateBrandStatis> brandStatis = new ArrayList<OosCateBrandStatis>();
        // 根据4位品牌编码汇总统计数据
        List<BiStoreOosEntity> list = null;
        // 9位编码集查询对应品牌信息
        List<BiStoreOosEntity> brands = null;
        if (GENERAL_OOS.equals(queryType)) {
            // 门店整体
            // 根据4位品牌编码汇总统计数据
            list = biStoreOosDaoService.queryStoreOosGeneralCateBrandStatis(storeCode, 
                    null, brandCodes, sumType, startIndex, limit);
            // 根据9位查询品牌编码对应的品牌信息
            brands = biStoreOosDaoService.queryOosGeneralBrandList(storeCode, brandCodes);
        } else if (HOT_OOS.equals(queryType)) {
            // 门店热销
            // 根据4位品牌编码汇总统计数据
            list = biStoreOosDaoService.queryStoreOosHotCateBrandStatis(storeCode, 
                    null, brandCodes, sumType, startIndex, limit);
            // 根据9位查询品牌编码对应的品牌信息
            brands = biStoreOosDaoService.queryOosHotBrandList(storeCode, brandCodes);
        } else if (MAIN_PUSH_OOS.equals(queryType)) {
            // 门店主推
            // 根据4位品牌编码汇总统计数据
            list = biStoreOosDaoService.queryStoreOosHotCateBrandStatis(storeCode, 
                    null, brandCodes, sumType, startIndex, limit);
            // 根据9位查询品牌编码对应的品牌信息
            brands = biStoreOosDaoService.queryOosHotBrandList(storeCode, brandCodes);
        }
        
        if (CollectionUtils.isNotEmpty(list) &&
                CollectionUtils.isNotEmpty(brands)) {
            // 组装数据
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            for (BiStoreOosEntity brand : brands) {
                List<String> brand9codes = map.get(brand.getBrand4code());
                if (null == brand9codes) {
                    brand9codes = new ArrayList<String>();
                    map.put(brand.getBrand4code(), brand9codes);
                }
                brand9codes.add(brand.getBrand9code());
            }
            for (BiStoreOosEntity entity : list) {
                OosCateBrandStatis statis = new OosCateBrandStatis();
                statis.setBrand4Code(entity.getBrand4code());
                statis.setBrand9codes(map.get(entity.getBrand4code()));
                statis.setBrandName(entity.getBrandName());
                statis.setCategoryCode(entity.getCateCode());
                statis.setCategoryName(ConfigUtil.getConfig(
                        ConfigConstants.SAWP_CONFIG_MAIN_PUSH_CATEGORY, entity.getCateCode()));
                statis.setOosNum(entity.getOosGdsNum());
                BigDecimal oosRate = new BigDecimal(entity.getOosGdsNum()).divide(new BigDecimal(entity.getGdsNum()), 3, RoundingMode.HALF_UP);
                statis.setOosRate(oosRate);
                statis.setPv(entity.getPv());
                statis.setUv(entity.getUv());
                
                brandStatis.add(statis);
            }
        }
        
        return brandStatis;
    }

    /**
     * 
     * 功能描述: 查询品类下品牌统计<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param cateCodes
     * @param startIndex
     * @param limit
     * @param queryType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<OosCateBrandStatis> getOosCateBrandStatisByCateCd(String storeCode, Set<String> cateCodes,
            int startIndex, int limit, String queryType, String sumType) {
        List<OosCateBrandStatis> brandStatis = new ArrayList<OosCateBrandStatis>();
        // 品类下品牌编码汇总统计数据
        List<BiStoreOosEntity> list = null;
        // 根据4位编码集查询对应品牌信息
        List<BiStoreOosEntity> brands = null;
        if (GENERAL_OOS.equals(queryType)) {
            list = biStoreOosDaoService.queryStoreOosGeneralCateBrandStatis(
                    storeCode, cateCodes, null, sumType, startIndex, limit);
            Set<String> brand4codes = new HashSet<String>();
            for (BiStoreOosEntity entity : list) {
                brand4codes.add(entity.getBrand4code());
            }
            brands = biStoreOosDaoService.queryOosGeneralBrandList(storeCode, brand4codes, cateCodes);       
        } else if (HOT_OOS.equals(queryType)) {
            list = biStoreOosDaoService.queryStoreOosHotCateBrandStatis(
                    storeCode, cateCodes, null, sumType, startIndex, limit);
            Set<String> brand4codes = new HashSet<String>();
            for (BiStoreOosEntity entity : list) {
                brand4codes.add(entity.getBrand4code());
            }
            brands = biStoreOosDaoService.queryOosHotBrandList(storeCode, brand4codes, cateCodes);       
        } else if (MAIN_PUSH_OOS.equals(queryType)) {
            list = biStoreOosDaoService.queryStoreOosMainPushCateBrandStatis(
                    storeCode, cateCodes, null, sumType, startIndex, limit);
            Set<String> brand4codes = new HashSet<String>();
            for (BiStoreOosEntity entity : list) {
                brand4codes.add(entity.getBrand4code());
            }
            brands = biStoreOosDaoService.queryOosMainpushBrandList(storeCode, brand4codes, cateCodes);       
        }
        
        if (CollectionUtils.isNotEmpty(list) &&
                CollectionUtils.isNotEmpty(brands)) {
            // 组装数据
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            for (BiStoreOosEntity brand : brands) {
                List<String> brand9codes = map.get(brand.getBrand4code());
                if (null == brand9codes) {
                    brand9codes = new ArrayList<String>();
                    map.put(brand.getBrand4code(), brand9codes);
                }
                brand9codes.add(brand.getBrand9code());
            }
            for (BiStoreOosEntity entity : list) {
                OosCateBrandStatis statis = new OosCateBrandStatis();
                statis.setBrand4Code(entity.getBrand4code());
                statis.setBrand9codes(map.get(entity.getBrand4code()));
                statis.setBrandName(entity.getBrandName());
                statis.setCategoryCode(entity.getCateCode());
                statis.setCategoryName(ConfigUtil.getConfig(
                        ConfigConstants.SAWP_CONFIG_MAIN_PUSH_CATEGORY, entity.getCateCode()));
                statis.setOosNum(entity.getOosGdsNum());
                BigDecimal oosRate = new BigDecimal(entity.getOosGdsNum()).divide(new BigDecimal(entity.getGdsNum()), 3, RoundingMode.HALF_UP);
                statis.setOosRate(oosRate);
                statis.setPv(entity.getPv());
                statis.setUv(entity.getUv());
                
                brandStatis.add(statis);
            }
        }
        
        return brandStatis;
    }
    
    /**
     * 
     * 功能描述: 缺货品类汇总<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param cateCodes
     * @param startIndex
     * @param limit
     * @param queryType
     * @param sumType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<OosCateBrandStatis> getOosCateStatisByCateCd(String storeCode, Set<String> cateCodes,
            int startIndex, int limit, String queryType, String sumType) {
        List<OosCateBrandStatis> brandStatis = new ArrayList<OosCateBrandStatis>();
        // 品类汇总统计数据
        List<BiStoreOosEntity> list = null;
        if (GENERAL_OOS.equals(queryType)) {
            list = biStoreOosDaoService.queryStoreOosGeneralCateBrandStatis(
                    storeCode, cateCodes, null, sumType, startIndex, limit);
        } else if (HOT_OOS.equals(queryType)) {
            list = biStoreOosDaoService.queryStoreOosHotCateBrandStatis(
                    storeCode, cateCodes, null, sumType, startIndex, limit);
        } else if (MAIN_PUSH_OOS.equals(queryType)) {
            list = biStoreOosDaoService.queryStoreOosMainPushCateBrandStatis(
                    storeCode, cateCodes, null, sumType, startIndex, limit);
        }
        
        if (CollectionUtils.isNotEmpty(list)) {
            // 组装数据
            for (BiStoreOosEntity entity : list) {
                OosCateBrandStatis statis = new OosCateBrandStatis();
                statis.setCategoryCode(entity.getCateCode());
                statis.setCategoryName(ConfigUtil.getConfig(
                        ConfigConstants.SAWP_CONFIG_MAIN_PUSH_CATEGORY, entity.getCateCode()));
                statis.setOosNum(entity.getOosGdsNum());
                BigDecimal oosGdsNum = new BigDecimal(entity.getOosGdsNum());
                BigDecimal gdsNum = new BigDecimal(entity.getGdsNum());
                BigDecimal oosRate = oosGdsNum.divide(gdsNum, 3, RoundingMode.HALF_UP);
                statis.setOosRate(oosRate);
                statis.setPv(entity.getPv());
                statis.setUv(entity.getUv());
                
                brandStatis.add(statis);
            }
        }
        
        return brandStatis;
    }

    @Override
    public ReturnMsg<List<OosStatisDetailRtn>> queryOosStatisDetails(String commKeyword, String brandCodes,
            String categoryCodes, int limit, String queryType, String sortType, int startIndex, String staffId) {
        ReturnMsg<List<OosStatisDetailRtn>> returnMsg = new ReturnMsg<List<OosStatisDetailRtn>>();
        List<OosStatisDetailRtn> data = new ArrayList<OosStatisDetailRtn>();
        // 取店员信息
        StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
        String storeCode = storeMan.getStoreCode();
        Set<String> brandCodeSet = new HashSet<String>();
        Set<String> cateCodeSet = new HashSet<String>();
        // 优先按品牌查询
        if (StringUtils.isNotBlank(brandCodes)) {
            // 查询品牌对应的缺货统计
            String[] args = brandCodes.split(",");
            for (String brandCd : args) {
                brandCodeSet.add(brandCd);
            }
        } else {
            // 品牌为空，则查询品类
            if (StringUtils.isNotBlank(categoryCodes)) {
                String[] args = categoryCodes.split(",");
                for (String cateCd : args) {
                    cateCodeSet.add(cateCd);
                }
            } else {
                // 品牌编码为空、品类编码为空，并判断此用户为店长
                if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
                    // 取店长的八大品类
                    for (Category cate : storeMan.getCategories()) {
                        cateCodeSet.add(cate.getCategoryCode());
                    }
                }
            }
        }
        
        List<BiStoreOosDetailEntity> list = biStoreOosDaoService.queryOosDetails(storeCode, brandCodeSet, 
                cateCodeSet, commKeyword, sortType, startIndex, limit, queryType);
        for (BiStoreOosDetailEntity entity : list) {
            OosStatisDetailRtn detailRtn = new OosStatisDetailRtn();
            detailRtn.setAvgPrice(entity.getNear30AvgPrice());
            detailRtn.setCategoryCode(entity.getCateCode());
            detailRtn.setCategogyName(ConfigUtil.getConfig(
                        ConfigConstants.SAWP_CONFIG_MAIN_PUSH_CATEGORY, entity.getCateCode()));
            detailRtn.setCommCode(entity.getCommCode());
            detailRtn.setCommName(entity.getCommName());
            detailRtn.setLastThirtysaleVolume(entity.getNear30SaleVolume());
            detailRtn.setSaleAmountRank(entity.getCateSaleAmountRank());
            detailRtn.setSaleVolumeRank(entity.getCateSaleVolumeRank());
            detailRtn.setYetdPv(entity.getTodayPv());
            detailRtn.setYetdUv(entity.getTodayUv());
            detailRtn.setMainPushFlag(entity.getMainPushFlg());
            detailRtn.setHotSaleFlag(entity.getHotSaleFlg());
            data.add(detailRtn);
        }
        returnMsg.setData(data);
        
        return returnMsg;
    }
}
